# -*- coding: utf-8 -*-
"""
Created on Tue Feb 17 16:40:25 2015

 install the following python package

 pip install httplib2
 pip install google-api-python-client
"""

import httplib2
import base64
import gspread

from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
from apiclient import errors
from email.mime.text import MIMEText


DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive'
GMAIL_SCOPE = 'https://mail.google.com/'
SHEET_SCOPE = 'https://spreadsheets.google.com/feeds'

DRIVE_CREDENTIAL_FILE = 'drive_credential.json'
GMAIL_CREDENTIAL_FILE = 'gmail_credential.json'
SHEET_CREDENTIAL_FILE = 'sheet_credential.json'
JSON_FILE = 'client_secrets.json'

SOURCE_MAIL_ADDRESS = 'email'
DESTINATION_MAIL_ADDRESS = 'email'
EMAIL_MESSAGE_TEXT = 'TEST DE MESSAGE PAR OAUTH'
EMAIL_SUBJECT_TEXT = 'OAUTH PYTHON'

FOLDER_ID = '0B9Yp8cxBtjfeflpyS0pUdi1pSm92eTd0SVBpbklRQzJPd1psMkR1RkI1azRoZkRfNEpZb2c'
# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def get_authentication(scope_name, credential_file):
    """
        This function return an object for OAUTH
    """
    storage = Storage(credential_file)

    flow = flow_from_clientsecrets(JSON_FILE, scope=scope_name)

    http = httplib2.Http()

    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run(flow, storage, http=http)

    http = credentials.authorize(http)

    if scope_name == DRIVE_SCOPE:
        print 'Drive scope Oauth'
        return build('drive', 'v2', http=http)
    if scope_name == GMAIL_SCOPE:
        # print 'Gmail scope Oauth'
        return build('gmail', 'v1', http=http)
    if scope_name == SHEET_SCOPE:
        # print 'Sheet scope Oauth'
        return gspread.authorize(credentials)
# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def handle_redirect(redirect_uri):
    # Parse authorization code out of url
    query_string = urlparse.urlsplit(redirect_uri).query
    authorization_code = urlparse.parse_qs(query_string).get('code', [])

    # parse_qs returns a list for every query param, just get the first one
    if len(authorization_code) > 0:
        return authorization_code[0]
    else:
        return None

# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------

def drive_insert_file(file_name):

    service = get_authentication(DRIVE_SCOPE, DRIVE_CREDENTIAL_FILE)

    media_body = MediaFileUpload(file_name, mimetype='*/*', resumable=True)

    body = {
        'title': file_name,
        'mimeType': '*/*',
        'parents': [{"kind": "drive#filelink", "id": FOLDER_ID}]
    }

    try:
        file = service.files().insert(body=body, media_body=media_body).execute()
        print 'File : %s uploaded correctly' % file_name
        FILE_ID = file['id']
        print 'ID File is : %s' % FILE_ID
        return [FILE_ID]
    except errors.HttpError, error:
        print 'An error occured: %s' % error


# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def drive_delete_file(file_id):

    service = get_authentication(DRIVE_SCOPE, DRIVE_CREDENTIAL_FILE)
    try:
        service.files().delete(fileId=file_id).execute()
    except errors.HttpError, error:
        print 'An error occured: %s' % error


# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def print_files_in_folder(folder_id):

    service = get_authentication(DRIVE_SCOPE, DRIVE_CREDENTIAL_FILE)

    page_token = None
    while True:
        try:
            param = {}
            if page_token:
                param['pageToken'] = page_token
            children = service.children().list(folderId=folder_id, **param).execute()
            for child in children.get('items', []):
                print child['id']
            #        file = service.files().get(fileId=child['id']).execute()
            #        print 'Title: %s' % file['title']
            page_token = children.get('nextPageToken')
            if not page_token:
                break
        except errors.HttpError, error:
            print 'An error occurred: %s' % error
            break


# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def gmailListMessage():

    service = get_authentication(GMAIL_SCOPE, GMAIL_CREDENTIAL_FILE)
    try:
        threads = service.users().threads().list(userId='me').execute()
        if threads['threads']:
            for thread in threads['threads']:
                print 'Thread ID: %s' % (thread['id'])
    except errors.HttpError, error:
        print 'An error occurred: %s' % error


# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def gmailSendMessage(user_id, message):

    service = get_authentication(GMAIL_SCOPE, GMAIL_CREDENTIAL_FILE)
    try:
        message = (service.users().messages().send(userId=user_id, body=message)
                   .execute())
        print 'Message Id: %s' % message['id']
        return message
    except errors.HttpError, error:
        print 'An error occurred: %s' % error


# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def gmailcreatemessage(sender, to, subject, message_text):

    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    return {'raw': base64.b64encode(message.as_string())}

# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------

if __name__ == '__main__':

    # File_Id = Drive_Insert_File('teleinfo.log')
    # print_files_in_folder(FOLDER_ID)
    # GmailListMessage()
    # GmailSendMessage('me',GmailCreateMessage(SOURCE_MAIL_ADDRESS, DESTINATION_MAIL_ADDRESS,
    #  EMAIL_SUBJECT_TEXT, EMAIL_MESSAGE_TEXT))
    service = get_authentication(SHEET_SCOPE, SHEET_CREDENTIAL_FILE)
    wks = service.open("teleinfo").sheet1
    val=wks.acell('E1').value
    print val
    val=wks.cell(1,2).value
    print val
    wks.update_cell(1,6,'Bogfo !')
    print 'end'